﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gift.DAL;
using Gift.Model;

namespace WebSite.cn
{
    public partial class ProfessionArea :BasePage
    {
        public StringBuilder SBProductList = new StringBuilder();
        readonly string sProductListFormat = " <tr>"
                                            + " <td class='leftpic'  style=\"width:200px;\"><img alt=\"{0}\" class='imgpic' src={1}  /></td>"
                                            + " <td valign='top' style=\" width:180px;\"><div class='list2'><div class='titleName'>{0}</div></div></td>"
                                            + " <td><div class='list2'  style=\"width:300px;\">{2}</div></td> "
                                            + " <td><div class='list2' style=\"width:120px\"><div class='cardprice'>兑换价:{3}</div></div> </td> "
                                            + " <td style=\" text-align:right;\"><a href='{4}' title=\"去兑换\"><img class='imglook'  src='images/toExchange.gif'  /></a></td></tr>";
        readonly Card theCard = new Card();
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly Shoppro theShoppro = new Shoppro();

        public string sLoginMessage = string.Empty;// "请输入礼品卡卡号和密码,可同时输入多张卡！";
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["backHref"] = Request.Url.PathAndQuery;
          
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["msg"]) && UserCardCodeList == null)
                {
                    sLoginMessage = "<font color='red' size='3'>请输入礼品卡卡号和密码，然后选择您要兑换的商品！</font>";
                }
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]) && string.IsNullOrEmpty(Request.QueryString["isView"]))
                {
                    return;
                }
            }
            BuildProductList();
        }

        protected void txtSubmit_Click(object sender, EventArgs e)
        {
            try
            {

                if (string.Compare(this.txtValidate.Text.Trim().ToUpper(), Session["checkCode"].ToString().ToUpper()) != 0)
                {
                    base.Response.Write("<script language='javascript'>alert('验证码不正确！请重新输入！');window.location.href='ProfessionArea.aspx';</script>");
                    base.Response.End();
                }
                try
                {
                    Int64.Parse(this.txtCardCode.Text.Trim());
                }
                catch
                {
                    base.Response.Write("<script language='javascript'>alert('卡格式不正确！请重新输入！');window.location.href='ProfessionArea.aspx';</script>");
                    base.Response.End();
                }

                dbCard oCard;
                oCard = theCard.GetModel(this.txtCardCode.Text.Trim(), this.txtPassword.Text.Trim());
                if (oCard != null)
                {
                    if (oCard.states == 0)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡还未发行，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else if (oCard.states == 2)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡券已被兑换，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else if (oCard.states == 3)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡已禁用，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else if (oCard.states == 4 || oCard.states == 6)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡还未激活，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else if (oCard.StartTime > DateTime.Now.Date)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡还未生效，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();
                    }
                    else if (oCard.endtime < DateTime.Now.Date)
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡已过有效时间，如有任何疑问请致电400-688-1077！');window.location.href='ProfessionArea.aspx';</script>");
                        base.Response.End();

                    }
                    else if (oCard.states == 1)
                    {

                        if (UserCardCodeList != null)
                        {
                            UserCard oCard1 = new UserCard();
                            Card oCardCampa = new Card();
                            if (UserCardCodeList[0].UserCardTypeId == oCard.cardtypeId.ToString())
                            {
                                bool bHasCard = false;
                                foreach (UserCard tempCard in UserCardCodeList)
                                {
                                    if (tempCard.UserCardCode == txtCardCode.Text.Trim())
                                    {
                                        bHasCard = true;
                                    }
                                }
                                if (!bHasCard)
                                {
                                    oCard1.UserCardId = oCard.cardid.ToString();
                                    oCard1.UserCardCode = txtCardCode.Text.Trim();
                                    oCard1.UserCardPassword = txtPassword.Text.Trim();
                                    oCard1.UserCardPrice = oCard.cardprice.ToString();
                                    oCard1.UserCardTypeId = oCard.cardtypeId.ToString();
                                    UserCardCodeList.Add(oCard1);
                                }
                            }
                            else
                            {
                                base.Response.Write("<script language='javascript'>alert('只能添加相同类型卡号！');window.location.href='ProfessionArea.aspx';</script>");
                                base.Response.End();
                            }
                        }
                        else
                        {
                            UserCardCodeList = new List<UserCard>();
                            UserCard oCard2 = new UserCard();
                            oCard2.UserCardId = oCard.cardid.ToString();
                            oCard2.UserCardCode = txtCardCode.Text.Trim();
                            oCard2.UserCardPassword = txtPassword.Text.Trim();
                            oCard2.UserCardPrice = oCard.cardprice.ToString();
                            oCard2.UserCardTypeId = oCard.cardtypeId.ToString();
                            UserCardCodeList.Add(oCard2);

                            if (re.ReadCookie("tempno") != null)
                            {
                                base.TempOrderId = re.ReadCookie("tempno");
                            }

                            SQLAccess.GreatDs("delete from DB_Car where carid in( select DB_Car.carid from DB_Car inner join DB_Shoppro on DB_Car.productid=DB_Shoppro.proid where DB_Car.flag=0 and DB_Car.temp='" + base.TempOrderId + "')");

                        }

                        if (!string.IsNullOrEmpty(base.Request.QueryString["pid"]))
                        {
                            DataTable dtProduct = new DataTable();
                            dtProduct = SQLAccess.GreatDs(" select CT.id from tbCardType CT join DB_Shoppro S on CT.ProfessionAreaTypeId = S.ProfessionAreaTypeId where S.proid=" + base.Request.QueryString["pid"]).Tables[0];

                            if (oCard.cardtypeId != int.Parse(dtProduct.Rows[0]["id"].ToString()))
                            {
                                Response.Redirect("ProfessionArea.aspx?page=1");
                                return;
                            }
                        }

                        if (!string.IsNullOrEmpty(Request.QueryString["pid"]))
                        {
                            DataTable table;
                            string str2;
                            string strPrice = "0";
                            string strContent = "";
                            string strProdNum = "0";
                            string strPid = "";
                            strPid = base.Request.QueryString["pid"];
                            strPrice = base.Request.QueryString["price"].ToString();
                            strContent = base.Request.QueryString["content"].ToString();
                            strProdNum = base.Request.QueryString["pronum"].ToString();

                            string tempId = string.Empty;
                            if (UserCardCodeList != null)
                            {
                                tempId = UserCardCodeList[0].UserCardCode;
                            }
                            else if (UserMemberId != null)
                            {
                                tempId = UserMemberId;
                            }
                            else
                            {
                                tempId = re.ReadCookie("tempno");
                            }
                            if (string.IsNullOrEmpty(tempId))
                            {
                                tempId = "0";
                            }

                            table = SQLAccess.GreatDs("select top 1 carid,pronum,price,score from DB_Car where productid=" + strPid + " and temp=" + tempId + " and contents='" + strContent + "' and flag=0").Tables[0];
                            if (table.Rows.Count > 0)
                            {
                                str2 = "update DB_Car set pronum=" + strProdNum + ",sumprice=" + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["price"]))) + ",sumscore=" + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["score"]))) + " where carid=" + table.Rows[0]["carid"].ToString() + "";
                            }
                            else
                            {
                                str2 = "insert into DB_Car (productid,memberid,pronum,state,flag,price,contents,temp,sumprice,score,sumscore) values (" + strPid + ",0," + strProdNum + ",0,0," + strPrice + ",'" + strContent + "'," + tempId + "," + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(strPrice))) + ",0,0)";
                            }
                            SQLAccess.DoSql(str2);
                            base.Response.Write("<script language='javascript'>window.location.href='account.aspx?type=1';</script>");
                            base.Response.End();
                        }

                     // ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('您的卡号通过验证，请选择您要兑换的礼品！');window.location.href='ProfessionArea.aspx?page=1&sid=" + Request.QueryString["sid"] + "';</script>");
                        base.Response.Write("<script type='text/javascript'>alert('您的卡号通过验证，请选择您要兑换的礼品！');window.location.href='ProfessionArea.aspx?page=1&sid=" + Request.QueryString["sid"] + "';</script>");
                        //base.Response.End();
                        return;
                    }
                    else
                    {
                        base.Response.Write("<script language='javascript'>alert('该卡已被使用！');window.location.href='ProfessionArea.aspx?sid=" + Request.QueryString["sid"] + "';</script>");
                        base.Response.End();
                    }
                }
                else
                {
                    base.Response.Write("<script language='javascript'>alert('卡号或密码不正确！');window.location.href='ProfessionArea.aspx?sid=" + Request.QueryString["sid"] + "';</script>");
                    base.Response.End();
                }
              

            }
            catch(Exception ex)
            {
                //LogFile.SendEmail(ex.Message.ToString());
            }
        }

        void BuildProductList()
        {

            DataSet ds = null;
            dbCard oCard;

            if (UserCardCodeList != null)
            {
                decimal dTotalCardPrice = 0;
                for (int i = 0; i < UserCardCodeList.Count; i++)
                {
                    dTotalCardPrice += decimal.Parse(UserCardCodeList[i].UserCardPrice);
                }
            
                oCard = theCard.GetModel(UserCardCodeList[0].UserCardCode, UserCardCodeList[0].UserCardPassword);

                ds = theShoppro.GetListByCardTypeId(int.Parse(UserCardCodeList[0].UserCardTypeId));
            }
            //else
            //{
            //    ds = theShoppro.GetListForProfession(Request.QueryString["typeid"]);
            //}
              
            if (ds != null && ds.Tables.Count > 0)
            {
                ProductBuilder(ds.Tables[0]);
            }
        }

        void ProductBuilder(DataTable table)
        {
            
            if (table.Rows.Count > 0)
            {
                foreach (DataRow row4 in table.Rows)
                {
                     System.Web.UI.HtmlControls.HtmlTableCell tdValue = new System.Web.UI.HtmlControls.HtmlTableCell();
                     tdValue.InnerHtml = row4["instruction"].ToString();
                     SBProductList.AppendFormat(sProductListFormat
                                          , row4["proname"].ToString()
                                          , "/uploadfile/product/" + row4["propic2"].ToString()
                                          , tdValue.InnerText
                                          , string.Format("{0:f}", row4["proprice1"])
                                          , "products_details.aspx?pid=" + row4["proid"].ToString() + "&sid=3"
                                          );                            
                }
            }
        }


        protected void productsList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                Label label = (Label)e.Item.FindControl("price");
                Label label2 = (Label)e.Item.FindControl("Label1");
                Image image = (Image)e.Item.FindControl("Image2");
                if ((label.Text == "0") || (label.Text == "0.00"))
                {
                    label.Text = label2.Text;
                }
                if (image.ImageUrl.ToString() == "")
                {
                    image.ImageUrl = System.Configuration.ConfigurationManager.AppSettings["DomainUrl"] +"/uploadfile/banner/" + info.info1("", "shopmopic");
                }

            }
        }

  
    }
}